from fastapi import FastAPI, HTTPException,APIRouter
from pydantic import BaseModel
from typing import List
import uvicorn

# 创建 FastAPI 应用实例
app02 = APIRouter()
# app = FastAPI(title="沃林学生考核成绩管理")


# 定义学生考核成绩的数据模型，对应“沃林学生考核成绩表”字段
class StudentScore(BaseModel):
    stu_id: str  # 学生编号
    exam_order: int  # 考核序次
    score: int  # 分数


# 模拟内存存储的学生成绩数据列表，可替换为数据库查询结果
student_scores = [
    StudentScore(stu_id="23051804", exam_order=1, score=88),
    StudentScore(stu_id="23051804", exam_order=2, score=81),
    StudentScore(stu_id="23100702", exam_order=1, score=77),
    StudentScore(stu_id="23022801", exam_order=1, score=92),
    StudentScore(stu_id="23100701", exam_order=1, score=85),
    StudentScore(stu_id="23100701", exam_order=2, score=90),
]


# 1. 获取成绩表所有信息
@app02.get("/scores/", response_model=List[StudentScore], summary="查询所有学生成绩")
async def get_all_scores():
    """返回系统中所有学生的所有考核成绩记录"""
    return student_scores


# 2. 通过学生编号查询所有学生成绩
@app02.get("/scores/student/{stu_id}", response_model=List[StudentScore], summary="按学生编号查所有成绩")
async def get_scores_by_stu_id(stu_id: str):
    """遍历成绩列表，筛选出指定学生编号的所有成绩"""
    result = [score for score in student_scores if score.stu_id == stu_id]
    if not result:
        raise HTTPException(status_code=404, detail=f"学生编号 {stu_id} 无成绩记录")
    return result


# 3. 增加学生成绩（存在则提示已存在）
@app02.post("/scores/", response_model=StudentScore, summary="添加学生成绩")
async def add_score(score: StudentScore):
    """先校验成绩是否已存在，存在则抛异常，否则添加到列表"""
    # 组合学生编号 + 考核序次作为唯一标识判断重复
    for exist_score in student_scores:
        if (
                exist_score.stu_id == score.stu_id
                and exist_score.exam_order == score.exam_order
        ):
            raise HTTPException(
                status_code=400,
                detail=f"学生 {score.stu_id} 考核序次 {score.exam_order} 的成绩已存在"
            )
    student_scores.append(score)
    return score


# 4. 通过学生编号和考核序次修改成绩
@app02.put("/scores/", response_model=StudentScore, summary="修改学生成绩")
async def update_score(score: StudentScore):
    """根据学生编号 + 考核序次定位成绩并修改"""
    for index, exist_score in enumerate(student_scores):
        if (
                exist_score.stu_id == score.stu_id
                and exist_score.exam_order == score.exam_order
        ):
            student_scores[index] = score
            return score
    raise HTTPException(
        status_code=404,
        detail=f"学生 {score.stu_id} 考核序次 {score.exam_order} 的成绩未找到"
    )


# 5. 通过学生编号和考核序次删除成绩
@app02.delete("/scores/", summary="删除学生成绩")
async def delete_score(stu_id: str, exam_order: int):
    """根据学生编号 + 考核序次定位成绩并删除"""
    for index, exist_score in enumerate(student_scores):
        if (
                exist_score.stu_id == stu_id
                and exist_score.exam_order == exam_order
        ):
            del student_scores[index]
            return {"message": f"学生 {stu_id} 考核序次 {exam_order} 的成绩已删除"}
    raise HTTPException(
        status_code=404,
        detail=f"学生 {stu_id} 考核序次 {exam_order} 的成绩未找到"
    )


